﻿using System.Security.Claims;
using ApiLib.AppStart;
using ApiLib.Helpers;
using ApiLib.Utils;
using Furion;
using Microsoft.AspNetCore.Http;

namespace ApiLib.Models;

/// <summary>
/// 基础认证接口
/// </summary>
public class BaseAuthorization : BaseAuthorization<SysUserinfo>;

/// <summary>
/// 基础认证接口,使用JWT
/// </summary>
public class BaseAuthorization<T> : AbstractBaseAuthorization where T : SysUserinfo
{
    /// <summary>
    /// 认证方法
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public override IBaseUser? Authorization(HttpRequest? request = null)
    {
        var token = GetToken();
        if (string.IsNullOrEmpty(token))
        {
            return default;
        }

        var userinfo = DbHelper.GetUserCache<T>(GlobalConstants.UserCachePrefix + token);
        if (userinfo != null)
        {
            return userinfo;
        }
        return null;

        //缓存里没有找到用户,从数据库中查询
        /* var sid = App.User?.FindFirstValue(ClaimTypes.Sid);
        var baseUser = GetUser(sid);
        if (baseUser == null)
        {
            throw CommonUtil.ActionException("用户不存在");
        }

        baseUser.InitPermissions();
        DbHelper.SetUserCache(GlobalConstants.UserCachePrefix + token, baseUser);
        return baseUser; */
    }

    /// <summary>
    /// 获取用户
    /// </summary>
    /// <param name="sid"></param>
    /// <returns></returns>
    public override IBaseUser? GetUser(string? sid)
    {
        if (sid == null)
        {
            return default;
        }

        if (int.TryParse(sid, out var id) && id > 0)
        {
            return DbHelper.Db.Queryable<T>()
                .IgnoreColumns(info => info.Password)
                .First(userinfo => userinfo.Id == id);
        }

        return default;
    }
}